package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;


    Logger logger = LoggerFactory.getLogger(GoodsService.class);

    public PageResult<SpuBo> querySpuByPage(Integer page, Integer rows, String key, Boolean saleable) {

        PageHelper.startPage(page,rows);

        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }

        if (null!=saleable){
            criteria.andEqualTo("saleable",saleable);
        }

        Page<Spu> spus = (Page<Spu>) this.spuMapper.selectByExample(example);

        //TODO 需要把查询的来的spu转换成spuBo

        List<SpuBo> spuBoList = new ArrayList<>();
        spus.forEach(spu -> {
            SpuBo spuBo = new SpuBo();
            //对两个对象的共有属性做值的对拷
            BeanUtils.copyProperties(spu,spuBo);


            // 2、查询spu的商品分类名称,要查三级分类
            List<String> names = this.categoryService.queryNamesByIds(
                    Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));


            //跨业务
            spuBo.setCname(StringUtils.join(names,"/"));


            Brand brand = this.brandService.queryBrandById(spu.getBrandId());

            spuBo.setBname(brand.getName());

            spuBoList.add(spuBo);

        });


        return new PageResult<>(spus.getTotal(),new Long(spus.getPages()),spuBoList);

    }


    @Transactional
    public void saveGoods(SpuBo spuBo) {

        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());

        //保存spu，自动回显id
        this.spuMapper.insertSelective(spuBo);


        SpuDetail spuDetail = spuBo.getSpuDetail();

        spuDetail.setSpuId(spuBo.getId());

        //保存spuDetail
        this.spuDetailMapper.insertSelective(spuDetail);


        List<Sku> skus = spuBo.getSkus();

        skus.forEach(sku -> {
            sku.setSpuId(spuBo.getId());

            sku.setCreateTime(new Date());

            sku.setLastUpdateTime(sku.getCreateTime());


            //保存sku，回显skuId
            this.skuMapper.insertSelective(sku);

            //顺带保存stoke库存

            Stock stock = new Stock();
            stock.setSkuId(sku.getId());

            stock.setStock(sku.getStock());

            this.stockMapper.insertSelective(stock);

        });
        sendMessage(spuBo.getId(),"insert");

    }

    public SpuDetail querySpuDetailById(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    public List<Sku> querySkuBySpuId(Long spuId) {

        Sku record = new Sku();

        record.setSpuId(spuId);

        List<Sku> skus = this.skuMapper.select(record);

        //查询sku时，顺便查询sku的库存
        skus.forEach(sku -> {

            sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        });
        return skus;
    }


    @Transactional
    public void updateGoods(SpuBo spuBo) {

        spuBo.setLastUpdateTime(new Date());

        //直接修改spu
        this.spuMapper.updateByPrimaryKeySelective(spuBo);

        //直接修改spuDetail
        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

//        判断谁是谁
//
//
//        如果sku的id为null，则一定是新增的，如果sku有id表示要修改的
//
//        id为null的直接新增，id有的直接修改。。。。。没回来的要下架


        Sku record = new Sku();

        record.setSpuId(spuBo.getId());

        //查询到所有的旧的sku
        List<Sku> oldSkus = this.skuMapper.select(record);


        List<Sku> newSkus = spuBo.getSkus();

        newSkus.forEach(newSku->{
            if (null==newSku.getId()){
                newSku.setSpuId(spuBo.getId());

                newSku.setCreateTime(new Date());

                newSku.setLastUpdateTime(newSku.getCreateTime());


                //保存sku，回显skuId
                this.skuMapper.insertSelective(newSku);

                //顺带保存stoke库存

                Stock stock = new Stock();
                stock.setSkuId(newSku.getId());

                stock.setStock(newSku.getStock());

                this.stockMapper.insertSelective(stock);
            }else{//要被修改的信息，把要被修改的从老旧的信息集合中清理
                newSku.setLastUpdateTime(new Date());
                newSku.setSpuId(spuBo.getId());

                this.skuMapper.updateByPrimaryKeySelective(newSku);

                Stock stock = new Stock();
                stock.setSkuId(newSku.getId());

                stock.setStock(newSku.getStock());

                //同步更改库存
                this.stockMapper.updateByPrimaryKeySelective(stock);

                //传入的箭头函数表示删除条件
                oldSkus.removeIf(oldSku-> oldSku.getId().longValue()==newSku.getId().longValue());

            }
        });


        //有要被下架的
        if (0!=oldSkus.size()){
            oldSkus.forEach(oldSku->{
                oldSku.setLastUpdateTime(new Date());
                oldSku.setEnable(false);

                this.skuMapper.updateByPrimaryKeySelective(oldSku);
            });
        }

        sendMessage(spuBo.getId(),"update");
    }

    public Spu querySpuById(Long spuId) {
        return this.spuMapper.selectByPrimaryKey(spuId);
    }

    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }
}
